/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
#include <iostream>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution
{
public:
    ListNode *reverseKGroup(ListNode *head, int k)
    {
        ListNode *ptr = head, *oldPtr = nullptr, *newHead = nullptr, *newTail = nullptr, *oldTail = nullptr;
        int counter = 0;
        int sz = 0;
        while (ptr != nullptr)
        {
            sz++;
            ptr = ptr->next;
        }
        sz = sz / k * k;
        ptr = head;
        ListNode *ans;
        bool first = true;
        for (int i = 0; i < sz; i++)
        {
            if (counter == k)
            {
                counter = 0;
                if (first)
                {
                    first = false;
                    ans = newHead;
                }
            }
            if (counter == 0)
            {
                oldTail = newTail;
                newHead = ptr;
                newTail = ptr;
            }
            counter++;
            oldPtr = ptr;
            ptr = ptr->next;
            oldPtr->next = newHead;
            newTail->next = ptr;
            newHead = oldPtr;
            if (oldTail != nullptr)
            {
                oldTail->next = newHead;
            }
        }
        if (counter == k)
        {
            counter = 0;
            if (first)
            {
                first = false;
                ans = newHead;
            }
        }
        return ans;
    }
};

ListNode *generate(int *arr, int n)
{
    ListNode *head = new ListNode(arr[0]);
    ListNode *ptr = head;
    for (int i = 1; i < n; i++)
    {
        ptr->next = new ListNode(arr[i]);
        ptr = ptr->next;
    }
    ptr = nullptr;
    return head;
}
void print(ListNode *node)
{
    ListNode *ptr = node;
    while (ptr != nullptr)
    {
        cout << ptr->val << " ";
        ptr = ptr->next;
    }
}
int main(int argc, char const *argv[])
{
    int a[] = {1};
    ListNode *head = generate(a, 1);
    Solution s;
    ListNode *reverse = s.reverseKGroup(head, 1);
    print(reverse);
    return 0;
}
